import React, { useState } from "react";
import { Card, Form, Button, InputNumber, Space, Input, Row, Col, AutoComplete, Upload } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useComponentDidMount } from "@/hooks";
import { fileUpload } from "@/services/common";
import type { UploadProps } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';
import { downloadFile } from "@/utils/util";
import { fetchDictTemplatePath } from "@/pages/BasicInfo/services";

const { Item } = Form;
const rules = [{required: true}];

type partTypes = {
  form: any,
  getDict: any
}
const labelCol = {span: 3}

const GoodsInfo = ({form, getDict}: partTypes) => {
  const productNames = getDict('productName');
  const [options, setOptions] = useState<{ value: string }[]>([]);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [entrustTemplatePath, setEntrustTemplatePath] = useState(null);


  const getPanelValue = (searchText: string) => {
    return !searchText ? [] : productNames.filter((v: any) => v.label.indexOf(searchText) >= 0)?.map((v: any) => ({value: v.label})) || []
  };

  const onSelect = (data: string) => {
    form.setFieldValue('productName', data);
  };

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };
  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => setFileList(newFileList);

  const uploadFileReq = ({file, filename, onSuccess, onError, data = {}}: any) => {
    const formData = new FormData();
    formData.append(filename, file);
    Object.keys(data).forEach(key => {
      formData.append(key, data?.[key]);
    })
    fileUpload(formData).then(
      res => {
        if (res?.code === '0') {
          onSuccess(res?.data);
        } else {
          onError(res?.data)
        }
      }
    )
  }

  useComponentDidMount(() => {
    form.setFieldsValue({
      shipmentIds: ['']
    });
    fetchDictTemplatePath({templateKey: "entrustTemplate"}).then(
      res => {
        setEntrustTemplatePath(res);
      }
    )
  })

  return (
    <Card title="货物/产品信息" className="mt15">
      <Form form={form} labelCol={labelCol}>
        <Item label="名称" name="cargoName" rules={rules}>
          <AutoComplete
            options={options}
            style={{ width: 200 }}
            onSelect={onSelect}
            onSearch={(text) => setOptions(getPanelValue(text))}
            placeholder="请输入商品名"
          />
        </Item>
        <Row style={{width: '100%'}}>
          <Col span={8}>
            <Item label="件数/箱" name="totalPieces" labelCol={{span: 9}} rules={rules}>
              <InputNumber style={{width: 250}} min={0} />
            </Item>
          </Col>
          <Col span={8}>
            <Item label="重量/KGS" name="totalWeight" labelCol={{span: 9}} rules={rules}>
              <InputNumber style={{width: 250}} min={0} />
            </Item>
          </Col>
          <Col span={8}>
            <Item label="体积/CBM" name="totalVol" labelCol={{span: 9}} rules={rules}>
              <InputNumber style={{width: 250}} min={0} />
            </Item>
          </Col>
        </Row>
        <Item label="Shipment ID" name="shipmentId">
          <Input.TextArea style={{width: 500}} rows={3} placeholder="多个shipment id用英文逗号分隔" />
        </Item>
        <Item label="委托单">
          <Space>
            <Item noStyle name="entrustFilePath" valuePropName="fileList" getValueFromEvent={normFile}>
              <Upload 
                maxCount={1} 
                customRequest={uploadFileReq}
                onChange={handleChange}
                fileList={fileList}
                data={{businessCode: 'entrust_file'}} 
              >
                {fileList.length >= 1 ? null : (
                  <Button style={{width: 200}} icon={<PlusOutlined />} type="default">上传</Button>
                )}
              </Upload>
            </Item>
            {entrustTemplatePath ? <Button type="link" onClick={() => downloadFile(entrustTemplatePath)}>模板下载</Button> : undefined}
          </Space>
        </Item>
      </Form>
    </Card>
  );
}
export default GoodsInfo;